package tum0r.webengine.command

import tum0r.webengine.config.ApplicationConfig
import tum0r.webengine.extension.convert
import tum0r.webengine.extension.errorLog

/**
 * 说明: 执行服务器命令
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/23 17:26
 */
class ExecuteCommand {
    /**
     * 执行服务器命令
     *
     * @param[commandString] 命令字符串
     */
    fun exec(commandString: String) {
        if (commandString.isBlank() || commandString.startsWith("#")) return
        // 处理命令
//        val commandArray = commandString.replace("\t{1,}", " ").replace("\r{1,}", " ").replace("\n{1,}", " ").replace(" {2,}", " ").split(" ")
        val regex = Regex("[\t\r\n]{2,}")
        val commandArray = regex.replace(commandString, " ").split(" ")

        // 获取参数
        val parameters = Array<Any?>(commandArray.size - 1) { null }
        for (i in 1 until commandArray.size)
            parameters[i - 1] = commandArray[i]

        // 处理类
        var className = ""
        var methodName = commandArray[0]
        val temp = commandArray[0].split("->")
        if (temp.size == 2) {
            className = temp[0]
            methodName = temp[1]
        }

        var flag = true
        for (item in ApplicationConfig.COMMAND_MAPPINGS) {
            if ((className == "" || className == item.className) && methodName == item.method.name && item.method.parameterCount == parameters.size) {
                item.method(ApplicationConfig.COMMAND_OBJECTS[item.index], *item.method.parameterTypes.convert(parameters))
                flag = false
                break
            }
        }
        if (flag) "未找到[${commandArray[0]}]命令".errorLog()
    }
}